package heapsort;

/**
 * 
 * @author song
 *
 */
public class HeapSort {

	private int []myarray;
	
	/**
	 *  constructor of Heapsort
	 * @param a  int []
	 */
	public HeapSort(int []a){
		this.myarray=a;
	}
	
	/**
	 * just do sort
	 */
	public void doSort() {

		for (int i = myarray.length; i > 1; i--) {
			heapAdjust(0, i - 1);
			swap(0,i-1);
		}
	}

	private void heapAdjust(int start, int end) {
		
		for (int i = end; (end - 1) / 2 > 0 || (end - 1) / 2 == 0; i--) {
			int fnode = (i - 1) / 2;
			if (i - 1 < 0) {
				break;
			}
			if (myarray[i] < myarray[i - 1]) {
				swap(i,i-1);
				if (myarray[i - 1] < myarray[fnode]) {
					swap(i-1,fnode);
				}
			}
			if (myarray[i] > myarray[i - 1]) {
				if (myarray[i - 1] < myarray[fnode]) {
					swap(i-1,fnode);

				}
			}
		}
	}
	
	private void swap(int mp, int np){
		int temp = 0;
		temp = myarray[mp];
		myarray[mp] = myarray[np];
		myarray[np] = temp;
	}

}